﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;
using Mighty.Common;
using Mighty.Brain;
using log4net;
using log4net.Config;

namespace Mighty.PlayingBoard
{
    public class Connector
    { 
        private Thread thread;
        private System.Timers.Timer threadTimer;
        private ManualResetEvent threadResetEvent;

        protected ActualStatus threadActualStatus;
        protected Object requestResult;
        protected bool requestIsTimeOut;

        protected static readonly ILog log = LogManager.GetLogger(typeof(PlayingBoard));

        protected int position;     // 관전자일경우 -1

        public Connector(int p)
        {
            position = p;
        }

        public Object Request(ActualStatus status)
        {
            threadActualStatus = status;
            requestResult = RequestInvoke();
            return requestResult;
        }

        public Object Request(ActualStatus status, int limitTime)
        {
            requestIsTimeOut = false;
            threadActualStatus = status;
            threadResetEvent = new ManualResetEvent(false);

            threadTimer = new System.Timers.Timer(limitTime);
            threadTimer.Elapsed += new ElapsedEventHandler(RequestTimer);
            threadTimer.AutoReset = false;
            threadTimer.Start();

            thread = new Thread(RequestThread);
            thread.Start();
            
            threadResetEvent.WaitOne();
            if (requestIsTimeOut)
            {
                throw new TicTimeOutException(status, position);
            }
            return requestResult;
        }

        private void RequestThread()
        {
            requestResult = RequestInvoke();
            threadTimer.Stop();
            threadResetEvent.Set();
        }

        private void RequestTimer(object source, ElapsedEventArgs e)
        {
            requestIsTimeOut = true;
            thread.Abort();
            threadResetEvent.Set();
        }

        virtual public void SetGameInfo(GameInfo g)
        {
        }


        virtual protected Object RequestInvoke()
        {
            return null;
        }
    }

}
